<template>

</template>

<script>
import axios from 'axios'
import Vue from 'vue'
import {baseUrl} from '../common/Common'

export default {
  name: 'HttpUtil',
  data() {
    return {}
  },
  methods: {}
}

export function httpRequest(method, url, token, data) {
  return new Promise((resolve, reject) => {
    axios({
      url: baseUrl + url,
      method: method,
      data: data,
      headers: {
        'Content-Type': 'application/json',
        'authorization': token
      }
    })
      .then((res) => {
          resovleResult(res, method)
          resolve(res.data)
        }
      )
      .catch((error) => {
        Vue.prototype.$message({
          message: error.message,
          type: 'error'
        })
      })
  })
}

export function get(url, token) {
  // 返回一个promise对象
  return httpRequest('get', url, token)
}

export function getSingle(url, token) {
// 返回一个promise对象
  return httpRequest('get', url, token)
}

export function post(url, token, data, noMsg) {
// 返回一个promise对象
  return httpRequest('post', url, token, data, noMsg)
}

export function update(url, token, data) {
// 返回一个promise对象
  return httpRequest('put', url, token, data)
}

export function del(url, token) {
// 返回一个promise对象
  return httpRequest('delete', url, token)
}

function resovleResult(res, method, noMsg) {
  var result = res.data
  if (result.code != '200') {
    Vue.prototype.$message.error(result.message)
  } else {
    if (method.toUpperCase() != 'GET' && noMsg) {
      Vue.prototype.$message({
        message: result.message,
        type: 'success'
      })
    }
  }

}

</script>

<style scoped>

</style>
